﻿using System.Web.Mvc;
using CodeContrib.Caching;
using CodeContrib.Web.Routing;
using CodeContribBlog.Data;

namespace CodeContribBlog.Web.Mvc.Controllers
{
	public abstract class BlogController : Controller
	{
		private Blog _blog;
		private BlogContext _blogContext;
		private static readonly ICache _cache;

		private User _user;

		public Blog Blog
		{
			get
			{
				if (_blog == null)
				{
					var cacheKey = string.Format("Blog_{0}", BlogId);

					object blog;

					if (!_cache.Find(cacheKey, out blog))
					{
						blog = BlogContext.Blogs.Find(BlogId);

						//_cache.Add(cacheKey, blog, null, TimeSpan.FromSeconds(5), DateTime.UtcNow.AddSeconds(5));
					}

					_blog = blog as Blog;
				}

				return _blog;
			}
		}

		public BlogContext BlogContext
		{
			get { return _blogContext ?? (_blogContext = new BlogContext(null, BlogId)); }
		}

		private int BlogId
		{
			get { return ((TenantRouteInfo)HttpContext.Items[TenantRoute.HttpContextKey]).TenantId; }
		}

		public new User User
		{
			get
			{
				if (base.User.Identity.IsAuthenticated)
				{
					return HttpContext.Items["__User"] as User;
				}

				return null;
			}
		}

		public int UserId
		{
			get
			{
				if (User == null)
				{
					return 0;
				}

				return User.Id;
			}
		}

		static BlogController()
		{
			_cache = new InMemoryCache();
		}

		protected override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			base.OnActionExecuted(filterContext);

			ViewBag.Blog = Blog;
		}

		protected override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			filterContext.ActionParameters["BlogId"] = Blog.Id;
		}
	}
}